/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.garagesale.user.web.action;

import com.garagesale.data.DBAccess;
import com.garagesale.data.Item;
import com.garagesale.web.form.ItemForm;
import com.garagesale.web.util.WebAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author christophe
 */
public class ViewItemAction extends org.apache.struts.action.Action
{

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {

        ItemForm itemForm = (ItemForm) form;


        if (null != request.getAttribute(Globals.ERROR_KEY))
        {
            ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);

            if (!errors.isEmpty())
            {
                // get list of categories that can be chosen for the item
                itemForm.setAvailableCategories(DBAccess.getInstance().getAllCategories());
                request.setAttribute("inError", "true");

                return mapping.findForward("edit");
            }

        }

        if (null == itemForm.getItemID())
        {

            // get list of categories that can be chosen for the item
            itemForm.setAvailableCategories(DBAccess.getInstance().getAllCategories());

            return mapping.findForward("edit");
        }

        Item foundItem = DBAccess.getInstance().retrieveByID(Item.class, itemForm.getItemID());

        // TODO: handle the case when no item is found

        // populate the item form with the found item
        itemForm.fromItem(foundItem);

        if (WebAction.EDIT.isAction(itemForm.getAction()))
        {
            // get list of categories that can be chosen for the item
            itemForm.setAvailableCategories(DBAccess.getInstance().getAllCategories());

            return mapping.findForward("edit");
        }

        return mapping.findForward("view");
    }
}
